import * as XLSX from 'xlsx';
import { message } from 'antd';
import { httpConfig } from 'containers/config/httpConfig';
/**
  exportExcel方法需要传入的参数
    1、headers --- 表头
    2、data --- 表格数据
    3、name --- 导出表格的名称，默认为导出表格数据
    4、arr --- 数组，每个单元格的大小，每个对象的key只必须是 wpx
    注意，导出表格的格式只能为xlsx，别的格式可能没数据或者不支持那种格式
 */

let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
let ipDeault = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? httpConfig.ipDeault : windowHost;

// 将pdf的base64格式转换为Blob
function base64toBlob(b64Data, contentType, sliceSize = 4) {
  let b = b64Data.toString();
  b64Data = b.split(',')[1];
  var byteCharacters = atob(b64Data);
  var byteArrays = [];
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);
    var byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }
    var byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  var blob = new Blob(byteArrays, { type: contentType });
  return blob;
}

const getColumnName = (index) => {
  let columnName = '';
  while (index >= 0) {
    columnName = String.fromCharCode(65 + (index % 26)) + columnName;
    index = Math.floor(index / 26) - 1;
  }

  return columnName;
}

let handleExcel = {
  // 导出 Excel
  exportExcel(headers, data, name = '导出表格数据', arr, format, sheetName) {
    let fileName = name + '.' + (format || 'xlsx');
    let headerData = []
    for (var i = 0; i < headers.length; i++) {
      headerData.push({ wpx: parseInt(headers[i].width || 100) })
    }
    // 单元格的大小
    let wpxArr = arr && arr.length > 0 ? arr : headerData;
    const _headers = headers
      .map((item, i) => Object.assign({}, {
        dataIndex: item.dataIndex,
        title: typeof (item.title) === "string" ? item.title : item.descripts,
        position: getColumnName(i) + '1'
      }))
      .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { dataIndex: next.dataIndex, v: next.title } }), {});

    const _data = data
      .map((item, i) => headers.map((headerItem, j) => Object.assign({}, {
        content: item[headerItem.dataIndex],
        position: getColumnName(j) + (i + 2)
      })))
      // 对刚才的结果进行降维处理（二维数组变成一维数组）
      .reduce((prev, next) => prev.concat(next))
      // 转换成 worksheet 需要的结构
      .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});
    // 合并 headers 和 data
    const output = Object.assign({}, _headers, _data);
    // 获取所有单元格的位置
    const outputPos = Object.keys(output);
    // 计算出范围 ,["A1",..., "H2"]
    const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;
    // 构建 workbook 对象
    const wb = {
      SheetNames: [sheetName || 'mySheet'],
      Sheets: {
        [sheetName || 'mySheet']: Object.assign(
          {},
          output,
          {
            '!ref': ref,
            '!cols': wpxArr,
          },
        ),
      },
    };

    XLSX.writeFile(wb, fileName, (err) => {
      if (err) {
        message.error(err)
      }
    });
  },

  // 后台导出，前端用iframe链接地址
  downloadExcel(url, fn) {
    if (!url) {
      message.error('导出异常，请稍后重试。');
      return;
    }
    try {
      var elemIF = document.createElement('iframe');
      elemIF.src = ipDeault + url;
      elemIF.style.display = 'none';
      document.body.appendChild(elemIF);
      fn && fn(); // 触发回调函数
      // 防止下载两次
      setTimeout(function () {
        document.body.removeChild(elemIF);
      }, 1000);
    } catch (error) {
      console.log(error);
    }
  },

  downloadPDF(base64Str, url, pdfName) {
    try {
      if (base64Str) {
        base64Str = 'data:application/pdf;base64,' + base64Str;
        let pdfFile = base64toBlob(base64Str, 'application/pdf');
        console.log('pdfFile')
        const blob = new Blob([pdfFile], { type: 'application/pdf' });  //指定打印文件类型pdf
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = decodeURI(pdfName); // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      } else {
        let openUrl = ipDeault + url;
        window.open(openUrl);
      }
    } catch (error) {
      console.log('error', error);
    }
  },

  importExcel(file, type) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      // 读取Excel文件
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        // 获取第一个工作表
        const worksheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[worksheetName];
        // 将工作表转换为JSON对象数组
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 'A', blankrows: false, defval: '' });
        if (type === 'keyVal') { // 第一行作为数据的key值，其他的数据作为val值，返回成列表需要的数据格式。栗子：[{dataIndex: 'code', width: '150px'}]
          let [columnData, ...dataRows] = jsonData;
          let tableData = dataRows.map(row => {
            return Object.fromEntries(Object.entries(columnData).map(([key, value]) => [value, row[key]]));
          });
          resolve(tableData);
        } else {
          resolve(jsonData);
        }
      };
      reader.onerror = () => {
        reject(reader.error);
      };
      reader.readAsArrayBuffer(file);
    });
  }
};

export { handleExcel };